package com.example.administrator.printoutindemo.mvp.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.example.administrator.printoutindemo.R;
import com.example.administrator.printoutindemo.SetActivity;
import com.example.administrator.printoutindemo.di.component.DaggerLogin_GongJuComponent;
import com.example.administrator.printoutindemo.di.module.Login_GongJuModule;
import com.example.administrator.printoutindemo.mvp.contract.Login_GongJuContract;
import com.example.administrator.printoutindemo.mvp.presenter.Login_GongJuPresenter;
import com.example.administrator.printoutindemo.mvp.ui.entity.Login_GongJu;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DeviceUtils;

import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import com.jess.arms.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import me.jessyan.retrofiturlmanager.RetrofitUrlManager;
import pub.devrel.easypermissions.EasyPermissions;

import static com.jess.arms.base.BaseConstants.HTTP_URL;
import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ACTIVITY_LOGIN_GONG_JU)
public class Login_GongJuActivity extends BaseActivity<Login_GongJuPresenter> implements Login_GongJuContract.View, EasyPermissions.PermissionCallbacks {


    @BindView(R.id.login_edit_account)
    EditText loginEditAccount;
    @BindView(R.id.login_edit_pwd)
    EditText loginEditPwd;
    @BindView(R.id.cb_jzmm)
    CheckBox cbJzmm;
    @BindView(R.id.login_btn_login)
    Button loginBtnLogin;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.btnRight)
    ImageView mBtnRight;
    private View.OnClickListener mRightListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            toSettingPage();
        }
    };

    private String[] permissions = {android.Manifest.permission.CAMERA, android.Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
    private boolean isSetGlobalDomain = false;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerLogin_GongJuComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .login_GongJuModule(new Login_GongJuModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_login__gong_ju; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    private void toSettingPage() {
        Intent intent = new Intent(Login_GongJuActivity.this, SetActivity.class);
        startActivity(intent);
    }

    /**
     * 跳转到新版的主页
     */
    private void toMainNengLiangEActivity() {
        Intent intent = new Intent(this, MainNengLiangEActivity.class);
        startActivity(intent);
        ArmsUtils.makeText(this, "登录成功");
//        finish();
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

        ArmsUtils.makeText(this, "相关权限获取成功");
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        ArmsUtils.makeText(this, "请同意相关权限，否则功能无法使用");

    }

    private boolean getPermission() {
        if (EasyPermissions.hasPermissions(this, permissions)) {
            return true;
        } else {
            EasyPermissions.requestPermissions(this, "需要获取您的照相使用权限", 103, permissions);
            return false;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        String httpUrl = mSharedPreferencesHelper.getString(HTTP_URL);
        if (TextUtils.isEmpty(httpUrl)) {
            toSettingPage();
        } else {
            if (!isSetGlobalDomain) {
                httpUrl = httpUrl.replace(" ", "");
                RetrofitUrlManager.getInstance().setGlobalDomain(httpUrl);
                isSetGlobalDomain = true;
            }
        }
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.activity_login__gong_ju));
        //getLogin_GongJuData();


        boolean isRemember = mSharedPreferencesHelper.getBoolean("user");
        if (isRemember) {
            String name = mSharedPreferencesHelper.getString("name1");
            String password1 = mSharedPreferencesHelper.getString("password1");
            loginEditAccount.setText(name);
            loginEditPwd.setText(password1);
            cbJzmm.setChecked(true);
        }

        tvVersion.setText("当前版本：" + DeviceUtils.getVersionName(this));

        mBtnRight.setImageDrawable(getResources().getDrawable(R.drawable.icon_setting));
        mBtnRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toSettingPage();
            }
        });
    }

    @Override
    public void getLogin_GongJuDataSuccess(Login_GongJu entityData) {

        if (entityData.getCode().equals("200")) {
            showMessage("登录成功");
            Login_GongJu.DataBean dataBean = entityData.getData();
            if (cbJzmm.isChecked()) {
                mSharedPreferencesHelper.putBoolean("user", true);
                mSharedPreferencesHelper.putString(BaseConstants.USERNAME1, getLoginAccount());
                mSharedPreferencesHelper.putString(BaseConstants.PASSWORD1, getLoginPwd());

            } else {
                mSharedPreferencesHelper.removeString(BaseConstants.USERNAME1);
                mSharedPreferencesHelper.removeString(BaseConstants.PASSWORD1);
            }

            mSharedPreferencesHelper.putString(BaseConstants.USERNAME, dataBean.getName());
            mSharedPreferencesHelper.putString(BaseConstants.MOBILE_PHONE, dataBean.getMobilePhone());
            mSharedPreferencesHelper.putString(BaseConstants.COMPANY, dataBean.getDepartName());
            mSharedPreferencesHelper.putString(BaseConstants.ROLE_NAME, BaseConstants.LoginRole.GONG_QI_JU.getValue());
            mSharedPreferencesHelper.putString(BaseConstants.UID, dataBean.getID());
            mSharedPreferencesHelper.putBoolean(BaseConstants.IS_LOGIN, true);

            toMainNengLiangEActivity();
        } else {
            showMessage(entityData.getMessage());
        }


    }

    private void getLogin_GongJuData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("loginName", getLoginAccount());
        map.put("password", getLoginPwd());
        mPresenter.getLogin_GongJuData(map);
    }


    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog(this);
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }


    @OnClick(R.id.login_btn_login)
    public void onViewClicked() {
        if (!getPermission()) return;

        if (TextUtils.isEmpty(getLoginAccount())) {
            showMessage("用户名不能为空");
            return;
        }
        if (TextUtils.isEmpty(getLoginPwd())) {
            showMessage("密码不能为空");
            return;
        }

        getLogin_GongJuData();
    }

    @NotNull
    private String getLoginAccount() {
        return loginEditAccount.getText().toString();
    }

    @NotNull
    private String getLoginPwd() {
        return loginEditPwd.getText().toString();
    }
}
